// pages/signinpage/index.js
const { ruleList, getSignData, toSign, getTask, toShare, guanzhu } = require("../../utils/api");

var lastFrameTime = 0;
var count = 0;
var ctx = null;
var factor = {
    speed: .008, // 运动速度，值越小越慢
    t: 0 //  贝塞尔函数系数
};
var that;
var timer = null; // 循环定时器


//签到
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {
            username: '',
            userid: '',
            userhead: '',
            point: '',
            signday: 0
        },
        signList: [],//签到
        tastList: [
            {
                id: 1, title: '新用户注册',
                icon: '../../static/taskimg/task-icon-1.png',
                point: '',
                intro: '',
                btn: '../../static/taskimg/quwancheng-btn.png',
                qulingqu: '../../static/taskimg/weilingqu-btn.png',
                finishbtn: '../../static/taskimg/yilingqu-btn.png',
                isLingqu: null,
                taskname: 'newreg',
                btnStatus: 0,
            },
            {
                id: 2, title: '分享小程序',
                icon: '../../static/taskimg/task-icon2.png',
                point: '',
                intro: '每日仅可领取一次积分奖励',
                btn: '../../static/taskimg/quwancheng-btn.png',
                qulingqu: '../../static/taskimg/weilingqu-btn.png',
                finishbtn: '../../static/taskimg/yilingqu-btn.png',
                isLingqu: null,
                taskname: 'evedayshare',
                btnStatus: 1,
            },
            {
                id: 3, title: '邀请新用户完成注册',
                icon: '../../static/taskimg/task-icon3.png',
                point: '',
                intro: '',
                btn: '../../static/taskimg/quyaoqing-btn.png',
                qulingqu: '../../static/taskimg/weilingqu-btn.png',
                finishbtn: '../../static/taskimg/yilingqu-btn.png',
                isLingqu: null,
                taskname: 'invitereg',
                btnStatus: 1,
            },
            {
                id: 4,
                title: '集齐系列图鉴并分享',
                icon: '../../static/taskimg/task-icon4.png',
                point: '',
                intro: '',
                btn: '../../static/taskimg/quwancheng-btn.png',
                qulingqu: '../../static/taskimg/weilingqu-btn.png',
                finishbtn: '../../static/taskimg/yilingqu-btn.png',
                isLingqu: null,
                taskname: 'aggseries',
                btnStatus: 0,
            },
            {
                id: 5,
                title: '关注“启蒙积木”公众号 ',
                icon: '../../static/taskimg/task-icon5.png',
                point: '',
                intro: '',
                btn: '../../static/taskimg/quwancheng-btn.png',
                qulingqu: '../../static/taskimg/weilingqu-btn.png',
                finishbtn: '../../static/taskimg/yilingqu-btn.png',
                isLingqu: null,
                taskname: 'guanzhu',
                btnStatus: 0,
            }
        ],
        showSign: false,//签到弹窗
        showRule: false,//规则弹窗
        ruleMsg: {},
        currentTimeStamp: "",
        todayPoint: '',//今日签到积分数
        lastClickTime: '',//上次点击的时间戳
        showStar: false,
        img_path: [
            [{
                x: 200,
                y: 400
            }, {
                x: 70,
                y: 300
            }, {
                x: -50,
                y: 150
            }, {
                x: 8,
                y: 0
            }],
            [{
                x: 200,
                y: 400
            }, {
                x: 30,
                y: 300
            }, {
                x: 80,
                y: 150
            }, {
                x: 8,
                y: 0
            }],
            [{
                x: 200,
                y: 400
            }, {
                x: 0,
                y: 90
            }, {
                x: 80,
                y: 100
            }, {
                x: 8,
                y: 0
            }]
        ]

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        that = this
        // 获取当前时间戳
        let timestamp = Date.now();
        // 将时间戳转成日期对象
        let date = new Date(timestamp);
        // 获取年月日
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        // 将月份和日期补齐两位数
        month = month < 10 ? '0' + month : month;
        day = day < 10 ? '0' + day : day;
        // 拼接成日期字符串
        let dateString = year + '-' + month + '-' + day;
        let currentTimeStamp = new Date(dateString).getTime()
        this.data.currentTimeStamp = currentTimeStamp
        this.toGetSignData()
        ctx = wx.createCanvasContext('mycanvas')

    },

    requestAnimationFrame(callback) {
        var currTime = new Date().getTime();
        //手机屏幕刷新率一般为60Hz，大概16ms刷新一次，这里为了使页面看上去更流畅自然,通过改变timedis的值可以控制动画的快慢
        var timedis = 16 - (currTime - lastFrameTime)
        var timeToCall = Math.max(0, timedis);
        var id = setTimeout(callback, timeToCall);
        lastFrameTime = currTime + timeToCall;
        return id;
    },
    drawImage: function (data, repeatcount) {
        if (repeatcount == 0) {
            return
        }
        var p10 = data[0][0]; // 三阶贝塞尔曲线起点坐标值
        var p11 = data[0][1]; // 三阶贝塞尔曲线第一个控制点坐标值
        var p12 = data[0][2]; // 三阶贝塞尔曲线第二个控制点坐标值
        var p13 = data[0][3]; // 三阶贝塞尔曲线终点坐标值

        var p20 = data[1][0];
        var p21 = data[1][1];
        var p22 = data[1][2];
        var p23 = data[1][3];

        var p30 = data[2][0];
        var p31 = data[2][1];
        var p32 = data[2][2];
        var p33 = data[2][3];

        var t = factor.t;

        /*计算多项式系数*/
        var cx1 = 3 * (p11.x - p10.x);
        var bx1 = 3 * (p12.x - p11.x) - cx1;
        var ax1 = p13.x - p10.x - cx1 - bx1;

        var cy1 = 3 * (p11.y - p10.y);
        var by1 = 3 * (p12.y - p11.y) - cy1;
        var ay1 = p13.y - p10.y - cy1 - by1;

        /*计算xt yt坐标值 */
        var xt1 = ax1 * (t * t * t) + bx1 * (t * t) + cx1 * t + p10.x;
        var yt1 = ay1 * (t * t * t) + by1 * (t * t) + cy1 * t + p10.y;

        /** 计算多项式系数*/
        var cx2 = 3 * (p21.x - p20.x);
        var bx2 = 3 * (p22.x - p21.x) - cx2;
        var ax2 = p23.x - p20.x - cx2 - bx2;

        var cy2 = 3 * (p21.y - p20.y);
        var by2 = 3 * (p22.y - p21.y) - cy2;
        var ay2 = p23.y - p20.y - cy2 - by2;

        /*计算xt yt坐标值*/
        var xt2 = ax2 * (t * t * t) + bx2 * (t * t) + cx2 * t + p20.x;
        var yt2 = ay2 * (t * t * t) + by2 * (t * t) + cy2 * t + p20.y;


        /** 计算多项式系数*/
        var cx3 = 3 * (p31.x - p30.x);
        var bx3 = 3 * (p32.x - p31.x) - cx3;
        var ax3 = p33.x - p30.x - cx3 - bx3;

        var cy3 = 3 * (p31.y - p30.y);
        var by3 = 3 * (p32.y - p31.y) - cy3;
        var ay3 = p33.y - p30.y - cy3 - by3;

        /*计算xt yt坐标值*/
        var xt3 = ax3 * (t * t * t) + bx3 * (t * t) + cx3 * t + p30.x;
        var yt3 = ay3 * (t * t * t) + by3 * (t * t) + cy3 * t + p30.y;

        factor.t += factor.speed;
        ctx.drawImage("../../static/taskimg/jifen-light-icon.png", xt1, yt1, 32, 36);
        ctx.drawImage("../../static/taskimg/jifen-light-icon.png", xt2, yt2, 34, 38);
        ctx.drawImage("../../static/taskimg/jifen-light-icon.png", xt3, yt3, 38, 40);
        ctx.drawImage("../../static/taskimg/jifen-light-icon.png", 20, xt2, 28, 32);
        ctx.drawImage("../../static/taskimg/jifen-light-icon.png", 10, yt3, 28, 32);
        ctx.drawImage("../../static/taskimg/jifen-light-icon.png", 1, xt1, 40, 44);
        ctx.draw();
        if (factor.t > 1) {
            factor.t = 0;
            clearTimeout(timer)
            if (repeatcount <= -1) {
                that.startTimer(repeatcount)
            } else {
                if (count < repeatcount) {
                    that.startTimer(repeatcount)
                    count++
                } else {
                    that.draworiginal()
                    count = 0;
                }
            }
        } else {
            timer = that.requestAnimationFrame(function () {
                that.drawImage(that.data.img_path, repeatcount)
            })
        }
    },


    //获得签到相关数据
    async toGetSignData() {
        await getSignData().then((res) => {

            if (res.errcode == 0) {
                this.setData({
                    signList: res.data.signs,

                    'tastList[0].point': res.data.tasks.newreg.score,
                    'tastList[1].point': res.data.tasks.evedayshare.score,
                    'tastList[2].point': res.data.tasks.invitereg.score,
                    'tastList[3].point': res.data.tasks.aggseries.score,
                    'tastList[4].point': res.data.tasks.guanzhu.score,

                    'tastList[0].isLingqu': res.data.tasks.newreg.status,
                    'tastList[1].isLingqu': res.data.tasks.evedayshare.status,
                    'tastList[2].isLingqu': res.data.tasks.invitereg.status,
                    'tastList[3].isLingqu': res.data.tasks.aggseries.status,
                    'tastList[4].isLingqu': res.data.tasks.guanzhu.status,
                    userInfo: {
                        username: res.data.user.nickname,
                        userid: res.data.user.id,
                        userhead: res.data.user.avatar,
                        point: res.data.user.score,
                        signday: res.data.consignday
                    }
                })

                // issign:  //0未签到  1已签到 2过期未签到 
                this.data.signList.forEach((signitem) => {
                    //今日
                    if (new Date(signitem.date).getTime() == this.data.currentTimeStamp) {
                        signitem.istoday = true
                        this.setData({
                            todayPoint: signitem.score
                        })
                    } else {
                        signitem.istoday = false
                    }

                    if (signitem.issign == 0 && signitem.istoday == false) {
                        signitem.bgcolor = "#C4CCFF"
                    } else if (signitem.issign == 0 && signitem.istoday == true) {
                        signitem.bgcolor = "#7957FB"
                    } else if (signitem.issign == 2) {
                        signitem.bgcolor = "#EDEDED"
                    } else if (signitem.issign == 1) {
                        signitem.bgcolor = "#EFEFFC"
                    }

                })
                this.setData({
                    signList: this.data.signList
                })

            }
        })
    },


    /**
     * 生命周期函数--监听页面显示
     */
    onShow() { },

    //签到规则
    onSignRule() {
        let params = {
            type: "2"
        }
        ruleList(params).then((res) => {
            if (res.errcode == 0) {
                this.setData({
                    showRule: true,
                    ruleMsg: res.data
                })
            } else {

            }
        })

    },

    onBack() {
        wx.navigateBack({
            delta: 1
        })
    },
    startTimer: function (repeatcount) {
        this.drawImage(this.data.img_path, repeatcount)
    },
    draworiginal() {
        ctx.drawImage("../../static/taskimg/jifen-light-icon.png", 30, 400, 30, 30);
        ctx.drawImage("../../static/taskimg/jifen-light-icon.png", 30, 400, 30, 30);
        ctx.drawImage("../../static/taskimg/jifen-light-icon.png", 30, 400, 30, 30);

        ctx.draw();
    },
    //任务按钮
    onTask(e) {
        // 1.该部分逻辑：新用户注册，分享小程序，关注公众号 为三个状态 0 1 2  ；0去完成   1去领取 （走领取接口） 2已领取  
        // 2.邀请新用户/集齐图鉴  只有显示去邀请按钮状态，无需走接口领取积分  
        // 3.btnStatus 为0可进行领取  1不可领取

        let taskinfo = e.currentTarget.dataset.item
        if ((taskinfo.isLingqu == 1 && taskinfo.btnStatus == 0) || (taskinfo.isLingqu == 1 && taskinfo.id == 2)) {
            let params = {
                type: taskinfo.taskname
            }
            getTask(params).then((res) => {

                if (res.errcode == 0) {

                    this.showStarFun()
                    setTimeout(function () { that.toGetSignData() }, 1000);


                } else {
                    wx.showToast({
                        title: res.errmsg,
                        icon: "none"
                    })
                }
            })
        }
        if (taskinfo.id == 4) {
            wx.switchTab({
                url: '/pages/picpage/index',
            });
        }

        if (taskinfo.id == 5 && taskinfo.isLingqu == 0) {
            wx.navigateTo({
                url: '/packageA/pages/gongzhonghao/index',
                success: (result) => {
                    guanzhu().then((res) => {
                    })
                },
            });
        }

    },

    //去签到
    async toSignin() {

        await toSign().then((res) => {
            if (res.errcode == 0) {
                this.setData({
                    showSign: true,
                })

            } else {
                wx.showToast({
                    title: res.errmsg,
                    icon: 'none'
                })
            }
        })

    },


    showStarFun() {
        let that = this
        that.setData({
            showStar: true
        })
        setTimeout(function () {
            that.setData({
                showStar: false
            })
            factor.t = 2
            count = 0
            that.startTimer(1)
        }, 500);
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage(e) {
        if (e.target.dataset.item.id == 2) {
            toShare().then((res) => {
                if (res.errcode == 0) {
                    this.toGetSignData()
                }
            })
        }
        return {
            title: '启蒙玩具积分商城',
            path: `/pages/homepage/home?shangjiuid=${this.data.userInfo.userid}`,// 路径，传递参数到指定页面。
            success: function (res) {

            },
        }
    },
    onUnload: function () {
        if (timer != null) {
            clearTimeout(timer)
        }

    },
})